package edu.utsa.cs.contactmanager.views;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import edu.utsa.cs.contactmanager.Contact;
import edu.utsa.cs.contactmanager.ContactManager;
import edu.utsa.cs.contactmanager.Group;
import edu.utsa.cs.contactmanager.R;

public class View_Search extends Activity{

	private Button searchButton;
	private EditText searchText;
	
	
	private ArrayList<Long> contactsFound;
	private ArrayList<Long> groupsFound;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_search);
        setFields();
        
	}
	
	@Override
    public void onResume(){
    	ContactManager.open();
    	super.onResume();
    };
    
    @Override
    public void onPause(){
    	ContactManager.close();
    	super.onPause();
    }
    
    private void setFields(){
    	searchText = (EditText)findViewById(R.id.searchText);
        
        searchButton = (Button)findViewById(R.id.searchButton);
        searchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	String searchString = searchText.getText().toString();
            	if(searchString == null || searchString.equals("") || searchString.equals(" ")){
            		Context context = getApplicationContext();
                	CharSequence text = "Enter search string.";
                	int duration = Toast.LENGTH_SHORT;

                	Toast toast = Toast.makeText(context, text, duration);
                	toast.show();

            	}
            	else
            		searchFor(searchString);
            }
        });
    }

	private void searchFor(String string){
    	
        contactsFound = new ArrayList<Long>();
        groupsFound = new ArrayList<Long>();
        
    	List<Contact> con = ContactManager.getContacts();
    	for(Contact c : con){
    		if(c.getFirstName().toLowerCase().contains(string.toLowerCase()) || c.getLastName().toLowerCase().contains(string.toLowerCase())){
    			contactsFound.add(c.getID());
    		}
    	}
    	
    	List<Group> groups = ContactManager.getGroups();
    	for(Group g : groups){
    		if(g.getName().toLowerCase().contains(string.toLowerCase())){
    			groupsFound.add(g.getID());
    		}
    	}
    	
    	Intent i = new Intent(this, View_SearchResults.class);
    	i.putExtra("contacts", contactsFound);
    	i.putExtra("groups", groupsFound);
    	i.putExtra("searchString", string);
    	startActivity(i);
    }

}
